<script setup>
import {ref} from "vue"
import {getPhoneCode, getVerify} from "@/api/verify.js";
import router from "@/router/index.js";
import {Message} from "@arco-design/web-vue";
import {userRegister} from "@/api/user.js";
import {encrypt} from "@/utils/encryption.js";
import LoginPageLogo from "@/components/LoginPageLogo.vue";

// 注册表单
const registerFormRef = ref()
const registerForm = ref({
  userAccount: "",
  userPassword: "",
  checkPassword: "",
  phone: "",
  code: ""
})
const agree = ref(false)
const registerRules = ref({
  userAccount: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "blur"
    },
    {
      match: /^[a-zA-Z0-9]{6,16}$/,
      message: '账号格式不正确！',
      trigger: 'blur'
    }
  ],
  userPassword: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur"
    },
    {
      match: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\S]{6,16}$/,
      message: '密码格式不正确',
      trigger: 'blur'
    }
  ],
  checkPassword: [
    {
      required: true,
      message: "请确认密码",
      trigger: "blur"
    },
    {
      match: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\S]{6,16}$/,
      message: '密码格式不正确',
      trigger: 'blur'
    },
    {
      validator: (value, cb) => {
        if (value !== registerForm.value.userPassword) {
          cb('两次输入的密码不一致')
        } else {
          cb()
        }
      }
    }
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "blur"
    },
    {
      match: /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/,
      message: '手机号格式不正确',
      trigger: 'blur'
    }
  ],
  code: [
    {
      required: true,
      message: "请输入短信验证码",
      trigger: "blur"
    },
    {
      match: /^\d{6}$/,
      message: '短信验证码格式不正确',
      trigger: 'blur'
    }
  ],
})

// 图形验证码
const base64Img = ref(null);

// 短信验证码获取表单
const phoneCodeForm = ref({
  phone: "",
  code: "",
  key: ""
})
// 短信验证码参数
let second = ref(60)
let totalSecond = ref(60)
let timer = ref(null)

// 获取图形验证码
const getPicCode = () => {
  getVerify()
    .then(res => {
      if (res.data.code === 1) {
        phoneCodeForm.value.key = res.data.data.key
        base64Img.value = res.data.data.img
      }
    })
    .catch(err => {
      console.log(err)
    })
}
getPicCode()

// 获取短信验证码
const getCode = () => {
  if (!/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/.test(registerForm.value.phone)) {
    Message.warning('请输入正确的手机号')
    return false
  }
  if (!/^\w{4}$/.test(phoneCodeForm.value.code)) {
    Message.warning('请输入正确的图形验证码')
    return false
  }
  if (!/^[a-zA-Z0-9]{6,16}$/.test(registerForm.value.userAccount)) {
    Message.warning('请输入正确的用户名')
    return false
  }
  if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\S]{6,16}$/.test(registerForm.value.userPassword)) {
    Message.warning('请输入正确的密码')
    return false
  }
  if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\S]{6,16}$/.test(registerForm.value.checkPassword)) {
    Message.warning('请输入正确的校验密码')
    return false
  }
  if (registerForm.value.checkPassword !== registerForm.value.userPassword) {
    Message.warning('两次输入的密码不一致')
    return false
  }
  phoneCodeForm.value = {
    phone: registerForm.value.phone,
    code: phoneCodeForm.value.code,
    key: phoneCodeForm.value.key
  }
  if (!timer.value && second.value === totalSecond.value) {
    getPhoneCode(phoneCodeForm.value).then((res) => {
      if (res.data.code === 1) {
        Message.success('短信验证码已发送,注意查收')
        // 开启倒计时
        timer.value = setInterval(() => {
          second.value--

          if (second.value < 1) {
            clearInterval(timer.value)
            timer.value = null
            second.value = totalSecond.value
          }
        }, 1000)
      }
    }).catch((err) => {
      console.log(err)
    })
  }
}

// 提交注册表单
const submitRegisterForm = () => {
  registerFormRef.value.validate(valid => {
    if (!valid) {
      if (agree.value === false) {
        Message.warning('请阅读用户协议')
        return false
      }
      const data = {
        userAccount: registerForm.value.userAccount,
        userPassword: encrypt(registerForm.value.userPassword),
        phone: registerForm.value.phone,
        code: registerForm.value.code
      }
      userRegister(data)
        .then(res => {
          if (res.data.code === 1) {
            Message.success('注册成功')
            router.replace('/login')
          }
        })
        .catch(error => {
          console.log(error)
        })
    } else {
      console.log("error submit!")
    }
  })
}
</script>

<template>
  <div id="register-page">
    <div class="register-form-container">
      <LoginPageLogo/>
      <div class="content">
        <div class="title">
          <div class="text-1">账号注册</div>
          <div class="text-2">您注册的账号将与手机号进行绑定</div>
        </div>
      </div>
      <div class="form">
        <a-form ref="registerFormRef" :model="registerForm" :rules="registerRules" :size="'large'">
          <a-form-item hide-label name="userAccount" field="userAccount" validate-trigger="blur">
            <a-input v-model="registerForm.userAccount" placeholder="请输入用户名"/>
          </a-form-item>
          <a-form-item hide-label name="userPassword" field="userPassword" validate-trigger="blur">
            <a-input-password v-model="registerForm.userPassword" placeholder="请输入密码(6~16位数字字母组合)"/>
          </a-form-item>
          <a-form-item hide-label name="checkPassword" field="checkPassword" validate-trigger="blur">
            <a-input-password v-model="registerForm.checkPassword" placeholder="请确认密码"/>
          </a-form-item>
          <a-form-item hide-label name="phone" field="phone" validate-trigger="blur">
            <a-input v-model="registerForm.phone" placeholder="请输入手机号"/>
          </a-form-item>
          <a-form-item hide-label name="code" field="code" validate-trigger="blur">
            <a-input v-model="registerForm.code" placeholder="请输入验证码"/>
            <a-button @click="getCode" class="code-btn" type="text">
              {{ second === totalSecond ? '获取短信验证码' : second + `秒后可重新发送` }}
            </a-button>
          </a-form-item>
          <a-form-item hide-label name="picCode">
            <a-input v-model="phoneCodeForm.code" placeholder="请输入图形验证码(点击重新获取)"/>
            <img v-if="base64Img" :src="'data:image/png;base64,' + base64Img" alt="图形验证码" @click="getPicCode">
            <img v-else alt="图形验证码" src="../../assets/code_fail.png" @click="getPicCode">
          </a-form-item>
          <a-form-item hide-label>
            <a-checkbox value="1" v-model="agree"></a-checkbox>
            <div class="check-text">我已同意本站
              <router-link to="/agree">《用户协议》</router-link>
            </div>
          </a-form-item>
        </a-form>
        <a-button type="primary" long @click="submitRegisterForm">注册</a-button>
        <div class="register-other">
          <span>忘记密码</span>
          <span @click="router.replace('/login')">前往登录</span>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
#register-page {
  display: flex;
  justify-content: center;
  height: 100vh;
  background-color: var(--color-bg-1);
}

.register-form-container {
  margin-top: 50px;
  width: 400px;
}

.content {
  margin-top: 20px;
}

.content .title .text-1 {
  font-size: 20px;
  color: rgb(var(--arcoblue-6));
}

.content .title .text-2 {
  margin-top: 5px;
  font-size: 14px;
  color: var(--color-text-2);
}

.form {
  margin-top: 20px;
}

.form .code-btn {
  width: 110px;
  height: 31px;
  border: none;
  font-size: 14px;
  color: rgb(var(--arcoblue-6));
  background-color: transparent;
}

.form img {
  width: 110px;
  height: 36px;
}

.check-text {
  margin-left: 5px;
  font-size: 14px;
  color: var(--color-text-2);
}

.check-text a {
  text-decoration: none;
  color: rgb(var(--arcoblue-6));
}

.register-other {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 14px;
  color: var(--color-text-3);
}

@media (max-width: 768px) {
  .register-form-container {
    margin-top: 20px;
  }
}

@media (max-width: 576px) {
  .register-form-container {
    margin-top: 20px;
    width: 90%;
  }
}
</style>
